<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import defaultProduct from '../assets/logo.jpg'  // 导入默认图片
import { useRouter } from 'vue-router'

const router = useRouter()

// 基础统计数据
const statistics = ref({
  totalOrders: 0,
  totalUsers: 0,
  totalProducts: 0,
  todayOrders: 0
})

// 最近订单数据
const recentOrders = ref([])

// 热销商品数据
const hotProducts = ref([])

// 系统公告数据

const notices = ref([
  { id: 1, title: '系统更新通知', time: '2024-03-10' },
  { id: 2, title: '新功能上线公告', time: '2024-03-09' },
  { id: 3, title: '促销活动预告', time: '2024-03-08' },
])

// 图表相关代码
let myChart = null

const initChart = () => {
  try {
    const chartDom = document.querySelector('.placeholder-chart')
    if (!chartDom) {
      console.error('找不到图表容器元素')
      return
    }

    // 销毁旧的实例
    if (myChart) {
      myChart.dispose()
    }

    myChart = echarts.init(chartDom)
    
    const option = {
      title: {
        text: '销售趋势',
        textStyle: {
          color: 'var(--text-color)'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['销售额', '订单量'],
        textStyle: {
          color: 'var(--text-color)'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        axisLine: {
          lineStyle: {
            color: 'var(--border-color)'
          }
        },
        axisLabel: {
          color: 'var(--text-color)'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: 'var(--border-color)'
          }
        },
        axisLabel: {
          color: 'var(--text-color)'
        }
      },
      series: [
        {
          name: '销售额',
          type: 'line',
          data: [820, 932, 901, 934, 1290, 1330, 1320],
          smooth: true,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(24,144,255,0.3)'
              },
              {
                offset: 1,
                color: 'rgba(24,144,255,0.1)'
              }
            ])
          },
          lineStyle: {
            color: '#1890ff'
          }
        },
        {
          name: '订单量',
          type: 'line',
          data: [120, 132, 101, 134, 90, 230, 210],
          smooth: true,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(82,196,26,0.3)'
              },
              {
                offset: 1,
                color: 'rgba(82,196,26,0.1)'
              }
            ])
          },
          lineStyle: {
            color: '#52c41a'
          }
        }
      ]
    }

    myChart.setOption(option)
  } catch (error) {
    console.error('初始化图表失败:', error)
  }
}

// 处理口大小变化
const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch('http://localhost:3001/api/admin/statistics', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    const data = await response.json()
    // console.log('统计数:', data)

    if (data.code === 200) {
      // 更新基础统计数据
      statistics.value = {
        totalOrders: data.data.totalOrders || 0,
        totalUsers: data.data.totalUsers || 0,
        totalProducts: data.data.totalProducts || 0,
        todayOrders: data.data.todayOrders || 0
      }

      // 更新最近订单数据
      recentOrders.value = data.data.recentOrders.map(order => ({
        id: order.order_id,
        orderNo: `ORD${order.order_id}`,
        customer: order.customer_name,
        amount: order.total_price,
        status: order.order_status,
        recipient_phone: order.recipient_phone,
        shipping_address: order.shipping_address,
        order_items: order.product_names?.split(',').map((name, index) => ({
          product_id: index + 1,
          product_name: name,
          product_price: Number(order.prices?.split(',')[index] || 0),
          quantity: Number(order.quantities?.split(',')[index] || 1),
          product_image: order.product_images?.split(',')[index] || null
        }))
      }))

      // 更新热销商品数据
      hotProducts.value = data.data.hotProducts || []

      // 更新图表数据
      if (data.data.salesTrend && myChart) {
        const dates = data.data.salesTrend.map(item => item.date)
        const orderCounts = data.data.salesTrend.map(item => item.order_count)
        const salesAmounts = data.data.salesTrend.map(item => item.sales_amount)

        myChart.setOption({
          xAxis: {
            data: dates
          },
          series: [
            {
              name: '销售额',
              data: salesAmounts
            },
            {
              name: '订单量',
              data: orderCounts
            }
          ]
        })
      }
    } else {
      throw new Error(data.message)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 生命周期钩子
onMounted(() => {
  fetchStatistics() // 获取统计数据
  
  // 延迟初始化图表，确保 DOM 已经渲染
  setTimeout(() => {
    initChart()
  }, 0)
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理事件监听和图表实例
  window.removeEventListener('resize', handleResize)
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
})

// 修改图片URL处理函数
const getImageUrl = (url) => {
  if (!url) return defaultProduct
  
  try {
    // 尝试解析JSON字符串
    const images = JSON.parse(url)
    if (Array.isArray(images) && images.length > 0) {
      // 使用第一张图片
      return `http://localhost:3001${images[0]}`
    }
  } catch (e) {
    // 如果解析失败，说明可能是普通字符串
    if (typeof url === 'string') {
      // 如果是完整URL则直接返回
      if (url.startsWith('http')) return url
      // 否则拼接基础URL
      return `http://localhost:3001${url}`
    }
  }
  
  return defaultProduct
}

// 处理图片加载错误
const handleImageError = (e) => {
  e.target.src = defaultProduct
}

// 添加订单详情相关的响应式变量
const showOrderDetail = ref(false)
const currentOrder = ref(null)
const orderDetailLoading = ref(false)

// 修改查看订单详情的方法
const viewOrderDetail = async (orderId) => {
  try {
    orderDetailLoading.value = true
    showOrderDetail.value = true
    
    // 从 recentOrders 中查找对应的订单
    const order = recentOrders.value.find(order => order.id === orderId)
    
    if (order) {
      currentOrder.value = {
        orderNo: order.orderNo,
        status: order.status,
        amount: order.amount,
        createTime: new Date().toLocaleString(), // 使用当前时间作为示例
        customer: order.customer,
        recipient_phone: order.recipient_phone || '暂无电话', // 添加联系电话
        shipping_address: order.shipping_address || '暂无地址', // 添加收货地址
        items: order.order_items.map(item => ({
          id: item.product_id,
          name: item.product_name,
          price: item.product_price,
          quantity: item.quantity,
          image: item.product_image
        }))
      }
    } else {
      throw new Error('未找到订单信息')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
  } finally {
    orderDetailLoading.value = false
  }
}

// 添加跳转方法
const goToOrders = () => {
  router.push('/orders')
}
</script>

<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <h3>总订单</h3>
        <p>{{ statistics.totalOrders }}</p>
        <div class="stat-footer">
          <span class="trend up">↑ 12%</span>
          <span class="period">较上周</span>
        </div>
      </div>
      <div class="stat-card">
        <h3>用户总数</h3>
        <p>{{ statistics.totalUsers }}</p>
        <div class="stat-footer">
          <span class="trend up">↑ 8%</span>
          <span class="period">较上周</span>
        </div>
      </div>
      <div class="stat-card">
        <h3>商品总数</h3>
        <p>{{ statistics.totalProducts }}</p>
        <div class="stat-footer">
          <span class="trend up">↑ 5%</span>
          <span class="period">较上周</span>
        </div>
      </div>
      <div class="stat-card">
        <h3>今日订单</h3>
        <p>{{ statistics.todayOrders }}</p>
        <div class="stat-footer">
          <span class="trend down">↓ 3%</span>
          <span class="period">较昨日</span>
        </div>
      </div>
    </div>

    <div class="dashboard-content">
      <!-- 左侧区域 -->
      <div class="content-left">
        <!-- 最近订单 -->
        <div class="recent-orders card">
          <div class="card-header">
            <h3>最近订单</h3>
            <button class="btn-text" @click="goToOrders">查看更多</button>
          </div>
          <table>
            <thead>
              <tr>
                <th>订单号</th>
                <th>客户</th>
                <th>金额</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="order in recentOrders" :key="order.id">
                <td>{{ order.orderNo }}</td>
                <td>{{ order.customer }}</td>
                <td>¥{{ order.amount }}</td>
                <td>
                  <span class="status" :class="order.status">
                    {{ order.status === 'confirmed' ? '已完成' : '待发货' }}
                  </span>
                </td>
                <td>
                  <button class="btn-text" @click="viewOrderDetail(order.id)">查看详情</button>
                  
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 销售趋势 -->
        <div class="sales-trend card">
          <div class="card-header">
            <h3>销售趋势</h3>
            <div class="card-header-extra">
              <select class="select-period">
                <option value="week">本周</option>
                <option value="month">本月</option>
                <option value="year">本年</option>
              </select>
            </div>
          </div>
          <div class="chart-container">
            <div class="placeholder-chart">
              销售趋势图表
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧区域 -->
      <div class="content-right">
        <!-- 热销商品 -->
        <div class="hot-products card">
          <div class="card-header">
            <h3>热销商品</h3>
          </div>
          <div class="product-list">
            <div v-for="product in hotProducts" :key="product.id" class="product-item">
              <img 
                :src="getImageUrl(product.image)"
                :alt="product.name"
                class="product-image"
                @error="handleImageError"
              >
              <div class="product-info">
                <h4>{{ product.name }}</h4>
                <p class="price">¥{{ product.price }}</p>
                <p class="sales">销量: {{ product.sales }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 系统公告 -->
        <div class="notice card">
          <div class="card-header">
            <h3>系统公告</h3>
          </div>
          <div class="notice-list">
            <div v-for="notice in notices" :key="notice.id" class="notice-item">
              <span class="notice-title">{{ notice.title }}</span>
              <span class="notice-time">{{ notice.time }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加弹窗组件 -->
    <div class="modal" v-if="showOrderDetail" @click.self="showOrderDetail = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>订单详情</h3>
          <button class="btn-close" @click="showOrderDetail = false">×</button>
        </div>
        
        <div v-if="orderDetailLoading" class="modal-loading">
          <i class="fa-solid fa-spinner fa-spin"></i>
          加载中...
        </div>
        
        <div v-else-if="currentOrder" class="modal-body">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">订单编号：</span>
                <span>{{ currentOrder.orderNo }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间：</span>
                <span>{{ currentOrder.createTime }}</span>
              </div>
              <div class="info-item">
                <span class="label">订单状态：</span>
                <span class="status" :class="currentOrder.status">
                  {{ currentOrder.status === 'confirmed' ? '已完成' : '待发货' }}
                </span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4>收货信息</h4>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">收货人：</span>
                <span>{{ currentOrder.customer }}</span>
              </div>
              <div class="info-item">
                <span class="label">联系电话</span>
                <span>{{ currentOrder.recipient_phone }}</span>
              </div>
              <div class="info-item">
                <span class="label">收货地址：</span>
                <span>{{ currentOrder.shipping_address}}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4>商品信息</h4>
            <table class="detail-table">
              <thead>
                <tr>
                  <th>商品</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>小计</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in currentOrder.items" :key="item.id">
                  <td class="product-cell">
                    <img 
                      :src="getImageUrl(item.image)" 
                      :alt="item.name"
                      class="product-thumb"
                      @error="handleImageError"
                    >
                    <span>{{ item.name }}</span>
                  </td>
                  <td>¥{{ item.price }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>¥{{ item.price * item.quantity }}</td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="3" class="total-label">总计：</td>
                  <td class="total-amount">¥{{ currentOrder.amount }}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
        
        <div v-else class="modal-error">
          未找到订单信息
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 24px;
  height: 100%;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.stat-card h3 {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stat-card p {
  margin: 16px 0;
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.stat-footer {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.trend {
  font-weight: 500;
}

.trend.up {
  color: #52c41a;
}

.trend.down {
  color: #ff4d4f;
}

.period {
  color: #999;
}

.card {
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.card-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.btn-text {
  border: none;
  background: none;
  color: #1890ff;
  cursor: pointer;
  padding: 4px 8px;
}

.btn-text:hover {
  background: rgba(24,144,255,0.1);
  border-radius: 4px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 16px 24px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 500;
  color: #666;
}

.status {
  padding: 4px 8px;
  border-radius: 2px;
  font-size: 12px;
}

.status.待发货 {
  background: #e6f7ff;
  color: #1890ff;
}

.status.已完成 {
  background: #f6ffed;
  color: #52c41a;
}

.status.待付款 {
  background: #fff7e6;
  color: #fa8c16;
}

.dashboard-content {
  flex: 1;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

.content-left {
  display: flex;
  flex-direction: column;
  gap: 24px;
  min-height: 0;
}

.content-right {
  display: flex;
  flex-direction: column;
  gap: 24px;
  min-height: 0;
}

.recent-orders {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.sales-trend {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  min-height: 400px;
  padding: 24px;
}

.placeholder-chart {
  height: 100%;
  background: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  border: 1px dashed #d9d9d9;
}

.product-list {
  padding: 16px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  background: #f5f5f5;
  transition: all 0.3s;
}

.product-image:hover {
  transform: scale(1.05);
}

.product-info {
  margin-left: 12px;
  flex: 1;
}

.product-info h4 {
  margin: 0 0 4px;
  font-size: 14px;
}

.price {
  color: #ff4d4f;
  margin: 0 0 4px;
  font-weight: 500;
}

.sales {
  color: #999;
  margin: 0;
  font-size: 12px;
}

.notice-list {
  padding: 16px;
}

.notice-item {
  display: flex;
  justify-content: space-between;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.notice-time {
  color: #999;
  font-size: 12px;
}

.select-period {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
}

/* 响应式布局调整 */
@media (max-width: 1400px) {
  .dashboard-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .content-right {
    grid-template-columns: 1fr;
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 4px;
  width: 800px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
}

.btn-close {
  border: none;
  background: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px 8px;
}

.btn-close:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px;
  font-size: 14px;
  color: #666;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  gap: 8px;
}

.label {
  color: #666;
  min-width: 80px;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
}

.detail-table th,
.detail-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.total-label {
  text-align: right;
  font-weight: 500;
}

.total-amount {
  font-weight: bold;
  color: #ff4d4f;
}

.status {
  padding: 4px 8px;
  border-radius: 2px;
  font-size: 12px;
}

.status.confirmed {
  background: #f6ffed;
  color: #52c41a;
}

.status.pending {
  background: #e6f7ff;
  color: #1890ff;
}

.product-thumb {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 8px;
}

.product-cell {
  display: flex;
  align-items: center;
}

.modal-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 48px;
  color: #666;
}
</style> 